package com.edee.bigday.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.edee.bigday.member.dao.MemberDao;
import com.edee.bigday.member.dao.MemberLevelDao;
import com.edee.bigday.member.entity.MemberEntity;
import com.edee.bigday.member.entity.MemberLevelEntity;
import com.edee.bigday.member.exception.MobileExistException;
import com.edee.bigday.member.exception.UserNameExistException;
import com.edee.bigday.member.service.MemberService;
import com.edee.bigday.member.vo.MemberLoginVo;
import com.edee.bigday.member.vo.MemberRegisterVo;
import com.edee.bigday.member.vo.SocialUser;
import com.edee.common.utils.HttpUtils;
import com.edee.common.utils.PageUtils;
import com.edee.common.utils.Query;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelDao levelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void register(MemberRegisterVo vo) {
        MemberDao memberDao = this.baseMapper;
        MemberEntity memberEntity = new MemberEntity();
        //设置会员默认等级：
        MemberLevelEntity levelEntity = levelDao.getDefultLevel();
        memberEntity.setLevelId(levelEntity.getId());

        //检查用户名和手机号是否在数据库已经存在。为了让Controller感知异常，应该使用异常机制。
        // 如果已经存在，则抛出异常给Service，Service再抛异常给Controller：
        checkMobileExist(vo.getMobile());
        checkUserNameExist(vo.getUserName());

        memberEntity.setMobile(vo.getMobile());
        memberEntity.setUsername(vo.getUserName());
        memberEntity.setNickname(vo.getUserName());

        //密码要加密存储：
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        memberEntity.setPassword(encode);

        //设置其它默认信息：

        memberDao.insert(memberEntity);
    }

    @Override
    public void checkMobileExist(String mobile) throws MobileExistException {
        MemberDao memberDao = this.baseMapper;
        Integer mobileCnt = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", mobile));
        if (mobileCnt > 0) {
            throw new MobileExistException();
        }
    }

    @Override
    public void checkUserNameExist(String username) throws UserNameExistException {
        MemberDao memberDao = this.baseMapper;
        Integer userNameCnt = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if (userNameCnt > 0) {
            throw new UserNameExistException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {
        String loginAccnt = vo.getLoginAccnt();
        String password = vo.getPassword();
        //1、从数据库中查询用户名或手机号等于用户输入的“账户”：
        MemberDao baseMapper = this.baseMapper;
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginAccnt).or().eq("mobile", loginAccnt));
        if (memberEntity == null) {
            //登录失败：
            return null;
        } else {
            //获取数据库的密码密文：
            String passwordFromDb = memberEntity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            //用户输入密码和数据库中存储的密码作比较：
            boolean matches = passwordEncoder.matches(password, passwordFromDb);
            if (matches) {
                //登录成功，重定向至首页：
                return memberEntity;
            } else {
                return null;
            }
        }
    }

    @Override
    public MemberEntity socialLogin(SocialUser socialUser) throws Exception {
        //注册和登录合并逻辑：
        String uid = socialUser.getUid();
        MemberDao memberDao = this.baseMapper;
        MemberEntity memberEntity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (memberEntity != null) {
            //当前社交用户已经注册过，只需为其更换令牌：
            MemberEntity memberEntityUpdate = new MemberEntity();
            memberEntityUpdate.setId(memberEntity.getId());
            memberEntityUpdate.setAccessToken(socialUser.getAccessToken());
            memberEntityUpdate.setExpiresIn(socialUser.getExpiresIn());
            memberDao.updateById(memberEntityUpdate);

            memberEntity.setAccessToken(socialUser.getAccessToken());
            memberEntity.setExpiresIn(socialUser.getExpiresIn());
            return memberEntity;
        } else {
            //没有查到当前社交用户对应的记录，则需要注册：
            MemberEntity register = new MemberEntity();
            try {
            //查询当前社交用户的账号信息（昵称、性别、电话等）：
                Map<String, String> query = new HashMap<>();
                query.put("access_token", socialUser.getAccessToken());
                query.put("uid", socialUser.getUid());
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), query);
                if (response.getStatusLine().getStatusCode() == 200) {
                    //查询社交用户信息成功：
                    String json = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSON.parseObject(json);
                    //昵称：
                    String name = jsonObject.getString("name");
                    //性别：
                    String gender = jsonObject.getString("gender");
                    //可以获取其它可能信息...
                    register.setNickname(name);
                    register.setGender("m".equals(gender) ? 1 : 0);
                }
            } catch (Exception e) {

            }
            register.setSocialUid(socialUser.getUid());
            register.setAccessToken(socialUser.getAccessToken());
            register.setExpiresIn(socialUser.getExpiresIn());

            memberDao.insert(register);
            return register;
        }
    }
}